package com.wtwd.campus.receiver;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.annotation.MsgType;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.entity.DeviceInfo;
import com.wtwd.campus.entity.MqGeneralValueResult;
import com.wtwd.campus.entity.MqLocationData;
import com.wtwd.campus.entity.MqMessage;
import com.wtwd.campus.h5_manager.entity.DeviceLog;
import com.wtwd.campus.h5_manager.service.DeviceLogService;
import com.wtwd.campus.service.DeviceInfoService;
import com.wtwd.campus.service.RedisService;
import com.wtwd.campus.utils.ReceiverUtils;
import com.wtwd.campus.vcom.common.Constant;
import com.wtwd.campus.vcom.entity.VcomRequestRecord;
import com.wtwd.campus.vcom.service.RequestRecordService;
import com.wtwd.campus.vcom.service.VcomDeviceInfoService;
import com.wtwd.campus.vcom.service.VcomPhoneService;
import com.wtwd.campus.vcom.utils.VcomPushUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Service
@MsgType(value = Constants.FACTORY_RESET)
public class FactoryResetReceiverHandler implements IReceiverHandler {
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private ReceiverUtils receiverUtils;
    @Autowired
    private DeviceLogService deviceLogService;
    @Autowired
    private RequestRecordService requestRecordService;
    @Autowired
    private VcomDeviceInfoService vcomDeviceInfoService;
    @Autowired
    private VcomPushUtils vcomPushUtils;
    @Resource
    private VcomPhoneService vcomPhoneService;
    @Resource
    private RedisService redisService;

    @Override
    public void handlerMessage(MqMessage mqMessage) {
        MqGeneralValueResult mqGeneralValueResult = (MqGeneralValueResult) mqMessage.getObject();
        String imei = mqGeneralValueResult.getImei();
        String commandNumber = mqGeneralValueResult.getCommandNumber();
        //处理指令回复的时间
        String deviceDate = mqGeneralValueResult.getDeviceDate();
        String deviceTime = mqGeneralValueResult.getDeviceTime();
        Long time = getTime(deviceDate, deviceTime);
        DeviceInfo deviceInfo = deviceInfoService.getDeviceByImei(imei);
        if (deviceInfo != null) {
            if (deviceInfo.getDeviceType().equals(Constants.VCOM_DEVICE)){//vcom设备的额外处理
                delVcom(imei,commandNumber);
            }
            MqLocationData mqLocationData = mqGeneralValueResult.getMqLocationData();
            if(mqLocationData != null){
                if (mqLocationData.getLatitude() != 0 && mqLocationData.getLongitude() != 0) {
                    //进行定位数据存储以及围栏告警记录的存储
                    deviceInfo = receiverUtils.dealLocation(mqGeneralValueResult.getMqLocationData(), time,deviceInfo,1);
                }
            }
            //修改设备信息
            deviceInfo.setLastUpTime((new Date()).getTime());
            deviceInfo.setWorkingPattern(Constants.DEFAULT_WORK_PATTERN);
            deviceInfo.setUpInterval(Constants.UP_INTERVAL);
            deviceInfoService.modifyDeviceInfo(deviceInfo);
            //删除缓存中的指令
            String delKey=Constants.FACTORY_RESET.concat("-").concat(commandNumber);
            receiverUtils.deleteCommandInRedis(imei, delKey);
            //完善指令下发记录
            receiverUtils.completeCommandRecord(Constants.FACTORY_RESET, imei, commandNumber, null, Constants.COMMAND_COMPLETE, time);
            //白名单的删除
            deviceInfoService.deleteWhiteListByDeviceId(deviceInfo.getDeviceId());
            //课堂模式的删除
            deviceInfoService.deleteClassPatternByDeviceId(deviceInfo.getDeviceId());
            //sos列表的删除
            deviceInfoService.deleteSOSList(deviceInfo.getDeviceId());
            //存储设备接收日志
            DeviceLog deviceLog = new DeviceLog();
            deviceLog.setCommandNumber(commandNumber);
            deviceLog.setSendUser(Constants.DEVICE_USER);
            deviceLog.setImei(imei);
            deviceLog.setBigType(Constants.MESS_TYPE);
            deviceLog.setType(Constants.FACTORY_RESET);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("设备号", imei);
            jsonObject.put("指令返回时间", time);
            jsonObject.put("经度", mqLocationData.getLongitude());
            jsonObject.put("纬度", mqLocationData.getLatitude());
            jsonObject.put("时间", mqGeneralValueResult.getDeviceDate());
            jsonObject.put("设备状态", mqGeneralValueResult.getDeviceStatus());
            deviceLog.setCmd(jsonObject.toJSONString());
            deviceLog.setSendTime(System.currentTimeMillis());
            deviceLog.setState(1);
            deviceLogService.addDeviceLog(deviceLog);
        }else {//如果查询出来设备是空的,可能设备已经被删除了
            //只完善指令下发记录表
            receiverUtils.completeCommandRecord(Constants.FACTORY_RESET, imei, commandNumber, null, Constants.COMMAND_COMPLETE, time);
            saveUnInStorage(imei);
            receiverUtils.cloaseChannel(imei);
        }
    }

    private void delVcom(String imei ,String commandNumber ){
        Map<String,Object> map = requestRecordService.getRequestRecordByCondition(imei,commandNumber, Constant.COMMAND_FACTORY_RESET);
        if (map!=null){
            // 推送requestId结果
            vcomPushUtils.pushAndUpdateRequestStatus((int)map.get("id"),(String)map.get("request_id"),Constant.STATUS_COMPLETE,Constant.COMMAND_FACTORY_RESET,imei);
            VcomRequestRecord nextSendCommand = requestRecordService.getNextSendCommand(imei, (String)map.get("request_id"), Constant.COMMAND_FACTORY_RESET);
            if(nextSendCommand != null){
                vcomDeviceInfoService.factoryDataReset(imei,nextSendCommand.getCommandNumber());
            }
            //1.删除vcom号码表中数据
            vcomPhoneService.deletePhone(imei);
            //2.完成所有未完成指令
            requestRecordService.CompleteAllInstructions(imei);
            //3.清除该设备所有缓存指令
            String key = Constants.COMMAND_PREFIX + imei;
            redisService.deleteKey(key);
        }
    }
}
